﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.WarehouseInsp.Buz.Interfaces;
using Microhard.Core.DBUtility;
using Microhard.WarehouseInsp.Buz.DataAccess;
using Microhard.WarehouseInsp.Buz.DTO;
using Microhard.Core;
using Microhard.WarehouseInsp.Buz.Msg;
using Microhard.WarehouseInsp.Buz.Models;
using Microhard.WarehouseInsp.Buz.BuzEnum;
using Microhard.WarehouseInsp.Buz.JHWorkflow;

namespace Microhard.WarehouseInsp.Buz.Impls
{
    public class RiskRecordsImpl : IRiskRecords
    {
        public byte[] DownLoadFile(Guid id)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            Attachment file = db.Attachments.Where(n => n.AttachmentID == id).SingleOrDefault();
            return file.Content;
        }

        public Microhard.Core.DBUtility.ExecutedResult Add(RiskRecordsModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();

            model.CreateTime = DateTime.Now;
            model.CreatorID = scope.CurrentUserID.ToString();
            model.CreatorName = scope.CurrentUserRealName;

            var op = model.ToEntity();
            try
            {
                db.RiskRecords.AddObject(op);
                db.SaveChanges();

                //发送提醒
                var prj = db.SupProjects.SingleOrDefault(p => p.ProjectID == model.ProjectID);
                StringBuilder content = new StringBuilder();
                content.Append("新增风险警报");
                content.Append(",项目:" + prj.Name);
                content.Append(",原因:" + model.RiskReason);
                content.Append(",处置情况:" + model.Exet);
                content.Append(",提交人:" + model.CreatorName + ",请注意!");
                SendAlertByJH.SendAlert(model.ProjectID, content.ToString());
            }
            catch (System.Exception ex)
            {
                rtn.ErrorMsg.Add(DBOperationFailedStatus.AddFailed, RiskRecordsMsg.AddFailed);
                Log.Error("IRiskRecords.Add", ex);
            }
            return rtn;
        }

        public Microhard.Core.DBUtility.ExecutedResult Update(RiskRecordsModel model)
        {
            ExecutedResult result = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();
            try
            {
                var entity = db.RiskRecords.SingleOrDefault(l => l.RiskRecordID == model.RiskRecordID);
                if (entity != null)
                {
                    entity.RiskReason = model.RiskReason;
                    entity.Exet = model.Exet;
                }
                db.SaveChanges();

                //发送提醒
                StringBuilder content = new StringBuilder();
                content.Append("风险警报变更");
                content.Append(",项目:" + entity.SupProject.Name);
                content.Append(",原因:" + model.RiskReason);
                content.Append(",处置情况:" + model.Exet);
                content.Append(",提交人:" + model.CreatorName + ",请注意!");
                SendAlertByJH.SendAlert(model.ProjectID, content.ToString());
            }
            catch (Exception ex)
            {
                result.ErrorMsg.Add(DBOperationFailedStatus.UpdateFailed, RiskRecordsMsg.UpdateFailed);
                Log.Error("IRiskRecords.Update", ex);
            }
            return result;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            WarehouseInspEntities db = new WarehouseInspEntities();
            var entity = db.RiskRecords.Where(l => ids.Contains(l.RiskRecordID));
            foreach (var e in entity)
            {

                try
                {
                    db.RiskRecords.DeleteObject(e);
                    var filelist = db.Attachments.Where(n => n.MainDataID == e.RiskRecordID);
                    foreach (var f in filelist)
                    {
                        db.Attachments.DeleteObject(f);
                    }
                }
                catch
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, string.Format(RiskRecordsMsg.DeleteFailed, e.RiskRecordID));
                }
            }
            if (result.ErrorMsg.Count == 0)
            {
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    result.ErrorMsg.Add(DBOperationFailedStatus.DeleteFailed, RiskRecordsMsg.DeleteFailed);
                    Log.Error("IRiskRecords.Delete", ex);
                }
            }
            return result;
        }

        public Microhard.Core.DBUtility.ExecutedResult Delete(RiskRecordsModel model)
        {
            throw new NotImplementedException();
        }

        public RiskRecordsModel GetModelByID(Guid id)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            var mcmp = db.RiskRecords.SingleOrDefault(c => c.RiskRecordID == id);
            if (mcmp != null)
            {
                return mcmp.ToModel();
            }
            return null;
        }

        public RiskRecordsModel GetModelByModel(RiskRecordsModel model)
        {
            throw new NotImplementedException();
        }

        public List<RiskRecordsModel> Query(RiskRecordsModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();

            IEnumerable<RiskRecord> entities = from b in db.RiskRecords
                                               where this.scope.PKID.Contains(b.RiskRecordID)
                                               select b;
            if (Model.ProjectID != Guid.Empty)
            {
                entities = from e in entities
                           where e.ProjectID == Model.ProjectID
                           select e;
            }
            totalCount = entities.Count();
            var pagedEntities = entities.OrderByDescending(p => p.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            if (pagedEntities != null && pagedEntities.Count > 0)
            {
                List<RiskRecordsModel> entities2 = pagedEntities.Select(m => m.ToModel()).ToList();
                return entities2;
            }
            return new List<RiskRecordsModel>();
        }


        public List<RiskRecordsModel> Query(RiskRecordsModel Model)
        {
            WarehouseInspEntities db = new WarehouseInspEntities();
            var mcmp = db.RiskRecords.Where(c => c.ProjectID == Model.ProjectID).ToList().Select(m => m.ToModel()).ToList();
            return mcmp;
        }

        public Microhard.Core.DBUtility.ScopeResult scope
        {
            set;
            get;
        }
    }
}
